﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using GC_VKMD.BusinessEntities.Vkontakte;
using GC_VKMD.MusicDownloader.Abstractions.Interfaces.Services;
using GC_VKMD.MusicDownloader.Constants.Vkontakte;

namespace GC_VKMD.MusicDownloader.Services
{
	public class VKService : IVKService
	{
		#region Variables

		private readonly string _token;

		private readonly string _userId;

		#endregion

		#region Constructors

		public VKService(string token, string userId)
		{
			if (string.IsNullOrWhiteSpace(token))
				throw new ArgumentNullException(string.Format("token"));
			_token = token;

			if (string.IsNullOrWhiteSpace(userId))
				throw new ArgumentNullException(string.Format("userId"));
			_userId = userId;
		}

		#endregion

		#region IVKService Members

		public int GetAudioTracksCount()
		{
			var url = string.Format(VKUrlTemplate.AudioGetCount, _userId, _token);

			var xml = new XmlDocument();
			xml.Load(url);

			var response = xml.SelectSingleNode("response");
			if (response == null) return 0;

			int result;
			int.TryParse(response.InnerText, out result);

			return result;
		}

		public IEnumerable<AudioTrack> GetAudio(int count)
		{
			var currentCount = GetAudioTracksCount();

			var url = string.Format(VKUrlTemplate.AudioGet, _userId, count < currentCount ? count : currentCount, _token);

			var xml = new XmlDocument();
			xml.Load(url);

			var result = new List<AudioTrack>();

			var audiosResponse = xml.SelectNodes("response/audio");
			if (audiosResponse != null)
			{
				audiosResponse.OfType<XmlNode>().ToList().ForEach(n =>
				{
					var title = n.SelectSingleNode("title");
					var artist = n.SelectSingleNode("artist");
					var album = n.SelectSingleNode("album");
					var trackUrl = n.SelectSingleNode("url");

					result.Add(new AudioTrack
					{
						Title = title != null ? title.InnerText : string.Empty,
						Artist = artist != null ? artist.InnerText : string.Empty,
						Album = album != null ? album.InnerText : string.Empty,
						Url = trackUrl != null ? trackUrl.InnerText : string.Empty,
					});
				});
			}

			return result;
		}

		#endregion
	}
}
